package com.example.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.dto.ElderlyBasicAddDTO;
import com.example.demo.dto.ElderlyDetailedAddDTO;
import com.example.demo.dto.ElderlyDetailedPageDTO;
import com.example.demo.exception.ElderlyDetailedAddException;
import com.example.demo.mapper.ElderlyDetailMapper;
import com.example.demo.pojo.ElderlyBasic;
import com.example.demo.pojo.ElderlyDetailed;
import com.example.demo.service.ElderlyBasicService;
import com.example.demo.service.ElderlyDetailedService;
import com.example.demo.utils.RedisIdWorker;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class ElderlyDetailedServiceImpl extends ServiceImpl<ElderlyDetailMapper, ElderlyDetailed> implements ElderlyDetailedService {
    @Resource
    private RedisIdWorker redisIdWorker;
    @Autowired
    private ElderlyBasicService elderlyBasicService;
    @Override
    @Transactional
    public void addElderlyDetail(ElderlyDetailedAddDTO elderlyDetailedAddDTO) {
        Long elderlyId = elderlyDetailedAddDTO.getElderlyId();

        // 判断这个elderlyId是否存在 这里可以开一个守护线程异步的来执行
        ElderlyBasic fatherNode = elderlyBasicService.getById(elderlyId);
        if (fatherNode == null) {
            throw new ElderlyDetailedAddException("没有相应的老人信息");
        }

        ElderlyDetailed elderlyDetailed = BeanUtil.copyProperties(elderlyDetailedAddDTO, ElderlyDetailed.class);
        elderlyDetailed.setId(redisIdWorker.nextId("elderly"));

        save(elderlyDetailed);
    }

    @Override
    public List<ElderlyDetailed> getElderlyDetail(ElderlyDetailedPageDTO elderlyDetailedPageDTO) {
        Integer page = elderlyDetailedPageDTO.getPage();
        Integer pageSize = elderlyDetailedPageDTO.getPageSize();
        String sortFiled = elderlyDetailedPageDTO.getSortFiled();
        Long id = elderlyDetailedPageDTO.getId();

        Page<ElderlyDetailed> p = Page.of(page, pageSize);
        p.addOrder(new OrderItem("id", false));
        lambdaQuery().eq(ElderlyDetailed::getElderlyId, id)
                .page(p);

        return p.getRecords();
    }
}
